<template>
  <div>
    <div class="form-class">
      <img class="logo" src="../assets/logo.png" />
      <el-card>
        <el-form
          :model="form"
          status-icon
          :rules="rules"
          ref="form"
          label-width="80px"
        >
          <div v-if="!forgetPwd">
            <div v-if="form.type === '1'">
              <!-- 账号密码登录 -->
              <el-form-item label="账号" prop="userName">
                <el-input v-model="form.userName" placeholder="请输入登录名" />
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input
                  type="password"
                  show-password
                  v-model="form.password"
                  placeholder="请输入密码"
                />
              </el-form-item>
            </div>

            <!-- 邮箱验证码登录 -->
            <div v-if="form.type === '2'">
              <el-form-item label="邮箱" prop="mail">
                <el-input v-model="form.mail" placeholder="请输入登录邮箱" />
              </el-form-item>
              <el-form-item label="验证码" prop="code">
                <el-input v-model="form.code" placeholder="请输入验证码">
                  <el-button
                    slot="append"
                    @click="sendCode"
                    :disabled="yzmState"
                    >{{ yzmText }}</el-button
                  >
                </el-input>
              </el-form-item>
            </div>
            <el-form-item>
              <el-button
                type="primary"
                @click="submit"
                :loading="loginState"
                style="width: 50%"
                >{{ loginText }}</el-button
              >
            </el-form-item>
            <el-button @click="forget" type="text">忘记密码?</el-button>
            <el-button @click="mailLogin" type="text">邮箱验证码登录</el-button>
          </div>
          <div v-else>
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入忘记密码账号的邮箱"
              />
            </el-form-item>
            <el-button @click="findPassword" type="primary">找回密码</el-button>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { isEmail } from "@/utils/validate";
export default {
  name: "login",
  data() {
    return {
      //表单对象
      form: {
        username: null,
        password: null,
        // 1、账号密码登录 2、邮箱验证码登录
        type: "1",
        code: null,
        mail: null,
      },
      //表单校验规则
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 30,
            message: "登录名称的长在2 ~ 30 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 100,
            message: "登录密码的长在6 ~ 30 个字符",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: false,
            validator: (rule, value, callback) => {
              if (!isEmail(value)) {
                callback(new Error("邮箱格式错误"));
              } else {
                callback();
              }
            },
          },
        ],
        mail: [
          {
            required: false,
            validator: (rule, value, callback) => {
              if (!isEmail(value)) {
                callback(new Error("邮箱格式错误"));
              } else {
                callback();
              }
            },
          },
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { min: 2, max: 6, message: "验证码的长为6个字符", trigger: "change" },
        ],
      },
      // 登录文字
      loginText: "登 录",
      // 登录状态
      loginState: false,
      // 忘记密码
      forgetPwd: false,
      yzmText: "发送验证码",
      yzmState: false,
    };
  },
  /**
   * 页面加载函数
   */
  created() {},
  /**
   * 存放所有的方法
   */
  methods: {
    submit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return this.$message.error("数据校验失败,请检查后提交");
        // 校验通过 加载按钮
        this.loginState = true;
        this.loginText = "登录中...";
        //校验成功后向后端请求
        this.$ajax
          .post("/user/login", this.form)
          .then((res) => {
            const tokenBody = res.data.data;
            let tokenHead = tokenBody.tokenHead;
            let token = tokenBody.token;
            // console.log('token', tokenHead + token)
            this.$store.commit("setToken", tokenHead + token); // 在vuex 中存入token
            this.$message.success("登录成功!");
            this.$router.push("/"); //跳转主页面
          })
          .catch(() => {
            this.loginState = false;
            this.loginText = "登 录";
          });
      });
    },
    /** 忘记密码 */
    forget() {
      this.forgetPwd = true;
    },
    /** 找回密码发送邮件 */
    findPassword() {
      this.$refs.form.validate((valid) => {
        if (!valid) return this.$message.error("数据校验失败,请检查后提交");
        //校验成功后向后端请求
        this.$ajax
          .post("/tool/forget/password", { receivers: [this.form.email] })
          .then((res) => {
            if (res.data.flag) {
              this.$message.success(res.data.message);
              this.forgetPwd = false;
            }
          });
      });
    },
    /** 邮箱登录 */
    mailLogin() {
      if (this.form.type === "1") {
        this.form.type = "2";
      } else {
        this.form.type = "1";
      }
      // 切换时移出表单校验结果
      this.$refs.form.clearValidate();
    },
    /** 发送验证码 */
    sendCode() {
      const pattern = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      // 判断邮箱是否填写
      if (!this.form.mail) return this.$message.error("请输入登录邮箱!");
      if (!pattern.test(this.form.mail))
        return this.$message.error("请输入正确的邮箱!");
      // 发送验证码
      this.$ajax
        .post("/tool/mailCode", { receivers: [this.form.mail] })
        .then((res) => {
          if (res.data.flag) {
            /**
             * setInterval： 每隔多少秒执行一次
             * setTimeout： 在多少秒后执行一次
             */
            let time = 60;
            const timer = setInterval(() => {
              this.yzmState = true;
              time--;
              if (time) {
                this.yzmText = time + "秒后重新发送";
              } else {
                clearInterval(timer);
                this.yzmText = "重新发送验证码";
                this.yzmState = false;
              }
            }, 1000);
            this.$message.success(res.data.message);
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
  },
};
</script>

<style scoped>
.form-class {
  box-shadow: #2c3e50;
  width: 30%;
  margin: 200px 450px auto;
}

.logo {
  width: 100px;
  height: 100px;
}
</style>
